package dao

import (
	"gin-mvc/models"
	"gin-mvc/models/admin"
	"gin-mvc/pkg/setting"
	"github.com/gomodule/redigo/redis"
	"github.com/jinzhu/gorm"
)

var (
	DB        *gorm.DB
	RedisConn *redis.Pool
)

// SetUpModel 初始化模型
func SetUpModel() {
	model := models.Model{}
	DB.Callback().Create().Replace("gorm:update_time_stamp", model.UpdateTimeStampForCreateCallback)
	DB.Callback().Update().Replace("gorm:update_time_stamp", model.UpdateTimeStampForUpdateCallback)
	DB.Callback().Delete().Replace("gorm:delete", model.DeleteCallback)

	// 自动迁移表结构
	DB.AutoMigrate(&admin.Tag{})
}

// SetUpMysql 初始化Mysql的连接
func SetUpMysql() {
	DB = InitMysqlPool()
	if setting.ServerSetting.RunMode == "debug" {
		DB.LogMode(true)
	}
}

// CloseMysqlConn 关闭mysql数据库的连接
func CloseMysqlConn() {
	if err := DB.DB().Close(); err != nil {
		panic("关闭数据库连接失败：" + err.Error())
	}
}

// SetUpRedis 初始化redis
func SetUpRedis() {
	RedisConn = InitRedisPool()
}

// CloseRedisConn 关闭redis连接
func CloseRedisConn() {
	if err := RedisConn.Close(); err != nil {
		panic("redis关闭连接失败：" + err.Error())
	}
}
